//
//  CDZQRCodeViewController.m
//  CDZQRCodeDemo
//
//  Created by Nemocdz on 2017/4/20.
//  Copyright © 2017年 Nemocdz. All rights reserved.
//

#import "CDZQRScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "CDZQRScanView.h"
#import <Photos/Photos.h>

@interface CDZQRScanViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,CDZQRScanDelegate>
@property (nonatomic ,strong) CDZQRScanView *scanView;
@property (nonatomic ,strong) UIImagePickerController *imagePicker;
@property (nonatomic ,assign) BOOL isOn;
@property (nonatomic ,strong) UIButton *lightBtn;
@end

@implementation CDZQRScanViewController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self turnTorchOn:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isOn = NO;
    [self setupViews];
    [self.scanView startScanning];
}

- (void)setupViews{
    self.view.backgroundColor = [UIColor blackColor];

    [self.navigationController setNavigationBarHidden:YES];

//    UIBarButtonItem *libaryItem = [[UIBarButtonItem alloc] initWithTitle:@"相册".rh_localized style:UIBarButtonItemStylePlain target:self action:@selector(openLibary)];
//    self.navigationItem.rightBarButtonItem = libaryItem;
    self.navigationItem.title = @"扫描二维码".rh_localized;
    [self.view addSubview:self.scanView];
    
    UIView *bar = [[UIView alloc] initWithFrame:CGRectZero];
    [bar setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.5]];
    [self.view addSubview:bar];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
    [titleLab setTextAlignment:NSTextAlignmentCenter];
    [titleLab setFont:[UIFont boldSystemFontOfSize:20]];
    [titleLab setTextColor:[UIColor whiteColor]];
    [titleLab setText:@"扫描中...".rh_localized];
    [bar addSubview:titleLab];

    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectZero];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -50, 0, 0)];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [bar addSubview:backBtn];

    UILabel *desLab = [[UILabel alloc] initWithFrame:CGRectZero];
    [desLab setTextAlignment:NSTextAlignmentCenter];
    [desLab setFont:[UIFont boldSystemFontOfSize:16]];
    [desLab setTextColor:[[UIColor whiteColor] colorWithAlphaComponent:0.8]];
    [desLab setNumberOfLines:2];
    [desLab setText:@"将二维码放入框内，即可自动扫描".rh_localized];
    [self.view addSubview:desLab];
    
    UIButton *lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [lightBtn setBackgroundColor:[UIColor clearColor]];
    [lightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    lightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [lightBtn setImage:[UIImage imageNamed:@"flashlight_off"] forState:UIControlStateNormal];
    [lightBtn addTarget:self action:@selector(openAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lightBtn];
    self.lightBtn = lightBtn;

    QMUIButton *photoBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [photoBtn setImage:[UIImage imageNamed:@"select_photo"] forState:UIControlStateNormal];
    [photoBtn addTarget:self action:@selector(openLibary) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:photoBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.bottom.mas_offset(0);
        make.left.mas_offset(0);
        make.height.mas_equalTo(@(kNavBarHeight));
    }];
    
    [bar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.height.mas_equalTo(@(kSafe_top+kTopBarHeight));
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(kNavBarHeight));
        make.centerX.mas_offset(0);
        make.bottom.mas_offset(0);
        make.width.mas_equalTo(150);
    }];
    
    CGFloat top = kNavBarHeight/2+(kUI_WINDOW_H - kUI_WINDOW_W*3/4)/2-60;
    [desLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kUI_WINDOW_W-60,40));
        make.centerX.mas_offset(0);
        make.top.mas_offset(top);
    }];
    
    CGFloat top1 = kNavBarHeight/2+(kUI_WINDOW_H - kUI_WINDOW_W*3/4)/2+kUI_WINDOW_W*3/4+30;
    [lightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.right.mas_offset(-65);
        make.top.mas_offset(top1);
    }];
    
    [photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.left.mas_offset(65);
        make.top.mas_offset(top1);
    }];
}

- (void)openLibary{
    if (![self isLibaryAuthStatusCorrect]) {
        [self showAlert:@"Photo Album Permission Is Required" action:nil];
        return;
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)backAction{
    [self.scanView stopScanning];
    [self.navigationController dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)openAction{
    if (self.isOn) {
       [self turnTorchOn:NO];
       self.isOn = NO;
    }else{
       [self turnTorchOn:YES];
       self.isOn = YES;
    }
    
}

// 打开/关闭手电筒
- (void)turnTorchOn:(BOOL)on{
    // 1.获取硬件设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash]){
        [device lockForConfiguration:nil];
        if (on) {
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
        } else {
            [device setTorchMode:AVCaptureTorchModeOff];
            [device setFlashMode:AVCaptureFlashModeOff];
        }
        [self.lightBtn setImage:[UIImage imageNamed:on?@"flashlight_on":@"flashlight_off"] forState:UIControlStateNormal];
        [device unlockForConfiguration];
    } else {

    }
}

- (NSString *)messageFromQRCodeImage:(UIImage *)image{
    if (!image) {
        return nil;
    }
    CIContext *context = [CIContext contextWithOptions:nil];
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
    CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
    NSArray *features = [detector featuresInImage:ciImage];
    if (features.count == 0) {
        return nil;
    }
    CIQRCodeFeature *feature = features.firstObject;
    return feature.messageString;
}


- (BOOL)isLibaryAuthStatusCorrect{
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus == PHAuthorizationStatusNotDetermined || authStatus == PHAuthorizationStatusAuthorized) {
        return YES;
    }
    return NO;
}


- (void)showAlert:(NSString *)message action:(void(^)())action{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定".rh_localized style:UIAlertActionStyleDefault handler:action];
    
    kWeakSelf;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.scanView startScanning];
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - imagePickerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info{
    [self turnTorchOn:NO];
    self.isOn = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSString *result = [self messageFromQRCodeImage:image];
    if (result.length == 0) {
        //[self showAlert:@"Qr Code Not Recognized" action:nil];
        [ProgressHUDManage showInfo:@"二维码无效".rh_localized];
        return;
    }
    kWeakSelf;
    if (self.resultCallBack) {
        self.resultCallBack(result);
    }
    [self dismissViewControllerAnimated:NO completion:nil];
    //不弹窗,直接回调
//    [self showAlert:result action:^{
//       
//    }];
}


#pragma mark - scanViewDelegate
- (void)scanView:(CDZQRScanView *)scanView pickUpMessage:(NSString *)message{
    [scanView stopScanning];
    kWeakSelf;
//    [self showAlert:message action:^{
        //[scanView startScanning];
//        [weakSelf callBack:message];
//    }];
    [self callBack:message];
}


- (void)callBack:(NSString *)message{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        if (self.resultCallBack) {
            self.resultCallBack(message);
        }
    }];
    
}


#pragma mark - get

- (CDZQRScanView *)scanView{
    if (!_scanView) {
        _scanView = [[CDZQRScanView alloc]initWithFrame:self.view.bounds];
        _scanView.delegate = self;
        _scanView.showBorderLine = YES;
    }
    return _scanView;
}


- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _imagePicker;
}

-(void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
